<?php

/*	LibFox - Simple library for XML-based backends.
	Copyright (C) 2008 LinFox Serviços em Informática LTDA.

	This file is part of LibFox.

	LibFox is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	LibFox is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>. */

require_once 'dao.php';
require_once 'user.php';

class user_dao extends dao
{
	public $key = 'user_id';
	protected $table = 'users';
	protected $model = 'user';
	protected $hash = 'sha512';

	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Verifica se o usuario esta autenticado
	 * 
	 * em caso que nao, tenta autenticar usando os valores no $_POST
	 * em caso que o usuario é autenticado, os dados sao guardados nas variaveis desse class
	 */
	public function auth()
	{
		if ($_POST['action'] == 'logout' || $_GET['action'] == 'logout') {
			$_SESSION = array();
			session_destroy();
			return false;
		} elseif (isset($_POST['login_username']) && isset($_POST['login_password']) && $_SESSION['vulpes_user_session'] != true) {
			$sql_user = '
				SELECT *
				FROM `'.$this->table.'`
				WHERE `username` = "' .mysql_escape_string($_POST['login_username']). '"
					AND `password` = "' .hash($this->hash, $_POST['login_password']). '"';
			$result_user = $this->db->query($sql_user);

			if ($user = $result_user->fetchObject($this->model)) {
				$_SESSION['vulpes_user_session'] = true;
				$_SESSION['vulpes_user_username'] = $user->username;
				$user->verified = true;
				return $user;
			} else {
				return false;
			}
		} elseif ($_SESSION['vulpes_user_session'] == true) {
			$sql_user = '
				SELECT *
				FROM `'.$this->table.'`
				WHERE `username` = "'.$_SESSION['vulpes_user_username'].'"';
			$result_user = $this->db->query($sql_user);
			if ($user = $result_user->fetchObject($this->model)) {
				$user->verified = true;
				return $user;
			}
		}
		return false;
	}

	function update_password(&$user,$password)
	{
		$key = $this->key;
		$sql_update_password = '
			UPDATE `'.$this->table.'`
			SET `password` = "'.hash('sha512', $password).'"
			WHERE `'.$this->key.'` = "'.$user->$key.'"';
		if (!$this->db->query($sql_update_password)) {
			throw new Exception('password_not_saved');
			return false;
		}
		return true;
	}
	
}

?>